package com.qch.concurrent.demo_04_notify_consumer;

/**
 * @Author qch
 * @Date 2021/7/26
 * 数组实现队列功能
 */
public class MyQueue {
    private String[] data = new String[10];
    private int putIndex = 0;
    private int getIndex = 0;
    //data中的元素个数
    private int size = 0;

    public synchronized void put(String element) {
        if (size == data.length) {
            //阻塞，等待
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        data[putIndex] = element;
        //放进去后唤醒等待的消费者线程
        notify();
        ++size;
        ++putIndex;
        if (putIndex == data.length)
            putIndex = 0;
    }

    public synchronized String get() {
        if (size == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String result = data[getIndex];
        ++getIndex;
        if (getIndex == data.length) getIndex = 0;
        --size;
        //唤醒生产者生产
        notify();
        return result;
    }
}
